package com.li.network.lab_4;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

public class ConnectThread extends Thread {
    private Socket client;
    public ConnectThread(Socket socket) {
        this.client = socket;
    }

    @Override
    public void run() {
        try {
            InputStream clientInputStream = client.getInputStream();
            OutputStream clientOutputStream = client.getOutputStream();
            System.out.println("client地址：" + client.getInetAddress() + ":" + client.getPort());
            //接收客户端的请求报文
            BufferedReader clientReader = new BufferedReader(new InputStreamReader(clientInputStream));
            ArrayList<String> requestStr = new ArrayList<>();
            String l1;
            StringBuilder sb = new StringBuilder();
            while (!(l1 = clientReader.readLine()).isEmpty()) {
//                System.out.println("请求内容：" + l1);
                requestStr.add(l1);
                sb.append(l1).append("\r\n");
            }
            sb.append("\r\n");
            //解析请求报文
            HttpRequest request = Parser.parseRequest(requestStr);
            String dest = request.getHeaders().get("Host");
            int port = Integer.parseInt(dest.substring(dest.indexOf(":") + 1));
            String host = dest.substring(0, dest.indexOf(":"));
            //与目标服务器建立连接
            Socket server = new Socket(host, port);
            System.out.println("server地址：" + host + ":" + port);
            InputStream serverInputStream = server.getInputStream();
            OutputStream serverOutputStream = server.getOutputStream();
            //发送请求报文
            serverOutputStream.write(sb.toString().getBytes(StandardCharsets.UTF_8));
            serverOutputStream.flush();
            CountDownLatch latch = new CountDownLatch(2);
            //转发服务器报文到客户端
            ExchangeThread responseExchange = new ExchangeThread(serverInputStream, clientOutputStream, latch);
            //转发客户端报文到服务器
            ExchangeThread requestExchange = new ExchangeThread(clientInputStream, serverOutputStream, latch);
            ExecutorService service = SingleThreadPool.getService();
            service.execute(responseExchange);
            service.execute(requestExchange);
            latch.await(120, TimeUnit.SECONDS);
            IOUtils.close(serverInputStream, serverOutputStream, server, clientInputStream, clientOutputStream, client);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
